package com.iot.ig.mqtt.receiver;

import cn.hutool.core.text.CharSequenceUtil;
import com.iot.ig.cache.LocalUserCache;
import com.iot.ig.common.Constants;
import com.iot.ig.websocket.util.WebSocketMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class MqttReceiver {

    @Resource
    private WebSocketMessageUtil webSocketMessageUtil;

    /**
     * 消息处理
     * <p>
     * ServiceActivator注解表明：当前方法用于处理MQTT消息，inputChannel参数指定了用于消费消息的channel
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        log.info("mqtt receiver init!");
        return message -> {
            String payload = message.getPayload().toString();

            // byte[] bytes = (byte[]) message.getPayload(); // 收到的消息是字节格式
            // 可以从缓存中获取用户信息，发送ws消息给指定用户
            String topic = Objects.requireNonNull(message.getHeaders().get("mqtt_receivedTopic")).toString();

            // 可以根据topic进行处理不同的业务类型
            log.info("接收到了消息,主题[{}]，负载：{}", topic, payload);
            // 发送websocket消息
            // 也可以在这里持久化
            String userName = getUserName();
            if(!userName.isEmpty()) {
                webSocketMessageUtil.sendMessageToUser(userName, payload);
            }
        };
    }

    /**
     * username获取方式不一定必须使用哪种方式，只要保证获取到用户名即可，可自行修改
     * @return
     */
    private String getUserName() {
        // 模拟用户
        List<String> userCache = LocalUserCache.getCache(Constants.WS_SESSION_KEY);
        if(CollectionUtils.isEmpty(userCache)) {
            return CharSequenceUtil.EMPTY;
        }
        return userCache.get(0);
    }
}
